<template>
  <div class="shopcart_wrapper-top">
    <div class="knife_container shopcart_data_no" v-if="!cartLength">
      <img src="../../images/data_no.png" width="150px" />
      <p class="shopcart-text"
      >当前采购清单空空如也～快去采购商品吧</p>
      <a class="shopcart_no_btn" @click="goBack">立即采购</a>
    </div>
    <div class="knife_container shopcart_wrapper" v-else>
      <div class="shopcart_box" :style="{'paddingBottom': submitHei + 20 + 'px'}">
        <el-row class="shopcart_tabhead">
          <el-col :span="2" class="check-el txt-rt">
            <span class="spanbox headcheckbox">
              <input type="checkbox" class="checkcss" :checked="checkAll" :disabled="allCheckDisabled" :class="{'not_allow': allCheckDisabled}" @change="goodAllChecked"/>
              <span class="checkspan iconfont"></span>
            </span>
            <span class="header-choose">全选</span>
          </el-col>
          <el-col :span="7">商品信息</el-col>
          <el-col :span="2" >商品单价</el-col>
          <el-col :span="4" >商品数量</el-col>
          <el-col :span="3" class="head-stock">库存状态</el-col>
          <el-col :span="4" class="head-product-total">商品总价(元)</el-col>
          <el-col :span="2">操作</el-col>
        </el-row>
        <!-- <div class="line-gray"></div> -->
        <!-- 活动列表 -->
        <template v-if="cartList.length > 0">
          <ul class="goods-box">
            <div class="activity-goods" v-for="(item, index) in madeData[0]" :key="index + Math.random()">
              <div class="act-title" v-if="ruleReady">
                <span class="act-tag">{{ item[2].name }}</span>
                <router-link :to="{ name: 'ScreenActivity', params: { activityId: item[0]}, query: {bannerUrl: item[2]['bannerUrl']}}">去凑单>></router-link>
                <span class="act-content">{{ item[2].str }}</span>
              </div>
              <li v-for="(skuItem, proIndex) in item[1]" :key="proIndex" class="good_info_li shopcart_body shopcart-bt">
                <span class="discount-card" v-if="skuItem.personalLimited">人均限购{{skuItem.personalLimitNum}}件</span>
                <div class="shop_check wid2 check-el">
                  <!-- <span class="OOS" v-if="(skuItem.stockLimit && skuItem.stock === 0 ">缺货</span> -->
                  <span class="spanbox">
                    <input type="checkbox" class="checkcss" :checked="skuItem.checked" @change="goodChecked(0, findIndex(0, skuItem.id))" />
                    <span class="checkspan iconfont"></span>
                  </span>
                </div>
                <div class="good_spe wid7">
                  <div class="shopcart_body_img">
                    <span class="discount-tag" v-if="skuItem.activity">活动</span>
                    <img :src="prefixImg + skuItem.goodsImg" @error="catchErrorImage($event)"/>
                  </div>
                  <router-link tag="div" :to="{name: 'productDetail',params: {commodityID:skuItem.goodsId }}" class="shopcart_img_text ellipsis pointer">
                    <span><em v-show="skuItem.brandName">【{{skuItem.brandName}}】</em>{{skuItem.goodsName}}<span v-show="skuItem.other"> - {{skuItem.other}} </span> </span>
                    <p class="shopcart_productname">{{skuItem.productName}}</p>
                    <span class="discount-time" v-if="skuItem.activity && isOverTime(skuItem.endTime)"> 活动已结束</span>
                    <!-- <span class="discount-time" v-else-if="skuItem.activity && skuItem.endTime">请在{{skuItem.endTime | endTimeFilter}}前结算商品,过期将被移除!</span> -->
                  </router-link>
                </div>
                <div class="wid2X">
                  <p class="pmt_price" v-if="skuItem.productPmtPrice">¥{{skuItem.productPmtPrice | floatPrices}}</p>
                  <p class="good_price" :class="{'old_price': skuItem.productPmtPrice}">¥{{skuItem.productPrice | floatPrices}}</p>
                </div>
                <!-- (:disabled="skuItem.inventoryStatus === '无货'") -->
                <div class="good_number wid4" style="margin: 0 auto;">
                  <el-input-number class="input-num-self"
                  @keydown.110.native.prevent=""
                  :value="skuItem.number"
                  :min="1"
                  :max="skuItem.stockLimit ? (skuItem.personalLimited ? skuItem.lastPersonalLimitNum : skuItem.stock) : 99999"
                  :step="skuItem.packingNum"
                  :id="'input_' + skuItem.id"
                  :ref="`prod_${findIndex(0, skuItem.id)}`"
                  @change="inputAmount($event, 0, findIndex(0, skuItem.id), skuItem)"></el-input-number>
                  </br>
                  <span class="discount-time overstock" v-if="skuItem.overstock">当前剩余可购{{skuItem.stock}}件</span>
                  <span class="discount-time overstock" v-if="skuItem.moreText">{{skuItem.moreText}}</span>
                </div>
                <div class="good_stock wid3"
                >{{skuItem.stock > 0 ? '有货' : skuItem.inventoryStatusDesc}}</div>

                <div class="good_total wid4" :class="{'active-price': parseFloat(skuItem.pmtAmount) > 0}">
                  ¥{{skuItem.pmtAmount > 0
                  ? (skuItem.number * skuItem.productPrice - skuItem.pmtAmount).toFixed(2)
                  : (skuItem.number * skuItem.productPrice).toFixed(2)}}
                    <p class="prefer-price" v-if="parseFloat(skuItem.pmtAmount) > 0 ">
                      已优惠¥{{skuItem.pmtAmount | floatPrices}}元
                    </p>
                </div>
                <div class="good_oprate wid2X el-icon-close" @click="deleteSingle(0, proIndex, skuItem.id)">
                </div>
                <div class="disabled-mask" v-if="skuItem.activity && isOverTime(skuItem.endTime)"></div>
              </li>
              <div class="act-footer" v-if="ruleReady"><span>{{ `￥ ${item[2].pri} ` }}</span>{{ `（已优惠 ￥${item[2].benefit}）` }}</div>
            </div>
            <div class="act-title gray"><span class="act-tag">普通商品</span></div>
            <div v-for="(item, index) in madeData[1]" :key="index" class="shopcart-bt">
              <li class="good_info_li shopcart_body">
                <span class="discount-card" v-if="item.personalLimited">人均限购{{item.personalLimitNum}}件</span>
                <div class="shop_check wid2 check-el">
                  <!-- <span class="OOS" v-if="(item.stockLimit && item.stock === 0 ">缺货</span> -->
                  <span class="spanbox">
                    <!-- :checked="checkedList[0][index] === 1" -->
                    <input type="checkbox" class="checkcss" :checked="item.checked" @change="goodChecked(0, findIndex(0, item.id))" />
                    <span class="checkspan iconfont"></span>
                  </span>
                </div>
                <div class="good_spe wid7">
                  <div class="shopcart_body_img">
                    <span class="discount-tag" v-if="item.activity">活动</span>
                    <img :src="prefixImg + item.goodsImg" @error="catchErrorImage($event)"/>
                  </div>
                  <router-link tag="div" :to="{name: 'productDetail',params: {commodityID:item.goodsId }}" class="shopcart_img_text ellipsis pointer">
                    <span><em v-show="item.brandName">【{{item.brandName}}】</em>{{item.goodsName}}<span v-show="item.other"> - {{item.other}} </span> </span>
                    <p class="shopcart_productname">{{item.productName}}</p>
                    <span class="discount-time" v-if="item.activity && isOverTime(item.endTime)"> 活动已结束</span>
                    <!-- <span class="discount-time" v-else-if="item.activity && item.endTime">请在{{item.endTime | endTimeFilter}}前结算商品,过期将被移除!</span> -->
                  </router-link>
                </div>
                <div class="wid2X">
                  <p class="pmt_price" v-if="item.productPmtPrice">¥{{item.productPmtPrice | floatPrices}}</p>
                  <p class="good_price" :class="{'old_price': item.productPmtPrice}">¥{{item.productPrice | floatPrices}}</p>
                </div>
                <!-- (:disabled="item.inventoryStatus === '无货'") -->
                <div class="good_number wid4" style="margin: 0 auto;">
                  <el-input-number class="input-num-self"
                  @keydown.110.native.prevent=""
                  :value="item.number"
                  :min="1"
                  :max="item.stockLimit ? (item.personalLimited ? item.lastPersonalLimitNum : item.stock) : 99999"
                  :step="item.packingNum"
                  :id="'input_' + item.id"
                  :ref="`prod_${findIndex(0, item.id)}`"
                  @change="inputAmount($event, 0, findIndex(0, item.id), item)"></el-input-number>
                  </br>
                  <span class="discount-time overstock" v-if="item.overstock">当前剩余可购{{item.stock}}件</span>
                  <span class="discount-time overstock" v-if="item.moreText">{{item.moreText}}</span>
                </div>
                <div class="good_stock wid3"
                >{{item.stock > 0 ? '有货' : item.inventoryStatusDesc}}</div>

                <div class="good_total wid4" :class="{'active-price': parseFloat(item.pmtAmount) > 0}">
                  ¥{{item.pmtAmount > 0
                  ? (item.number * item.productPrice - item.pmtAmount).toFixed(2)
                  : (item.number * item.productPrice).toFixed(2)}}
                    <p class="prefer-price" v-if="parseFloat(item.pmtAmount) > 0 ">
                      已优惠¥{{item.pmtAmount | floatPrices}}元
                    </p>
                </div>
                <div class="good_oprate wid2X el-icon-close" @click="deleteSingle(0, index, item.id)">
                </div>
                <div class="disabled-mask" v-if="item.activity && isOverTime(item.endTime)"></div>
              </li>
            </div>

          </ul>
        </template>
    </div>

    <!-- 去结算 -->
    <div class="submit_box" :style="{'height': `${submitHei}px`, marginTop: `-${submitHei}px`}" ref="refSubmit">
      <div class="submit_order">
        <div class="check-two left">
          <div class="check-el txt-rt">
            <span class="spanbox headcheckbox">
              <input type="checkbox" class="checkcss" :checked="checkAll" :disabled="allCheckDisabled" :class="{'not_allow': allCheckDisabled}" @change="goodAllChecked"/>
              <span class="checkspan iconfont"></span>
            </span>
            <span class="header-choose">全选</span>
          </div>
        </div>

        <div class="left">
          <a class="color-blue btn_text" @click="fetchBatchInquire">批量询货</a>
          <a class="btn_text" @click="deleteSelected">删除</a>
          <span>共计{{allAmount}}件商品，已选择{{activeAmount}}件</span>
        </div>
        <div class="right">
          合计(未使用红包及代金券）<span class="submit_price" v-if="madeData">{{(selectedPrice - madeData[2]).toFixed(2)}}</span>元
          <button :disabled="!selectIdArr.length" :class="{'not_allow':!selectIdArr.length}" class="submit_btn subm-button" @click="submitOrder">去结算</button>
        </div>
      </div>
    </div>
    </div>
  </div>
</template>
<script>
  import {Col, Row, InputNumber, Checkbox, Tooltip, Dialog, Button} from 'element-ui'
  import {deleteCart, getBatchConsult, changeProNumber, voucherActivity, activityFull} from '@/service/get-data'
  import {mapState, mapActions} from 'vuex'
  import {prefixImg, stock} from '@/tool/index'
  import {flattenDepth, throttle, countDown} from '@/tool/tool'
  import {getSession, removeSession} from '@/config/mUntils'
  // const MAXMARA = '无货'
  export default {
    components: {
      elCol: Col,
      elRow: Row,
      elInputNumber: InputNumber,
      elCheckbox: Checkbox,
      elTooltip: Tooltip,
      elDialog: Dialog,
      elButton: Button
    },
    data () {
      return {
        prefixImg,
        stock,
        submitHei: 62,
        voucherStatus: false, // 送券活动是否在进行,true正在进行,false 未开始或结束
        checkedList: [],
        cartList: [],
        activeCartIndex: 0, // 显示的购物车
        transX: 'translateX(0)',
        activeAmount: 0, // 选中的数量
        allAmount: 0, // 全部的数量
        selectedPrice: 0, // 选中商品的总价
        selectIdArr: '', // 选中商品的字符串 "1,2,3,4,5"
        allCheckDisabled: false, // 全选的可否点击
        strstock: '', // 批量询货参数
        calcCount: 0,
        num: 0,
        discountObj: null,
        noticeShow: false,
        level: 0,
        timerresult: '',
        globalTimer: null,
        fielsStatus: 0, // 活动状态
        ruleList: {}, // 活动规则
        ruleReady: false // 活动规则是否请求完成
      }
    },
    computed: {
      ...mapState({
        nowDiscount: state => state.user.discount,
        cartLength: state => state.shopcart.cartlength,
        cartLists: state => state.shopcart.cartlist,
        shopcartId: state => state.shopcart.shopCartId,
        getMoreGoodsOver: state => state.activity.getMoreGoodsOver
      }),
      madeData () {
        const obj = {}
        const arr = [] // 普通商品list
        const brr = [] // 活动商品组list
        let benefitSum = 0 // 满享优惠总金额
        if (!this.cartList.length) return
        this.cartList[0].productList.forEach((item) => {
          if (item.activityId && this.ruleList.hasOwnProperty(item.activityId)) {
            if (!obj.hasOwnProperty(item.activityId)) {
              obj[item.activityId] = []
            }
            obj[item.activityId].push(item)
          } else {
            arr.push(item)
          }
        })
        for (const i in obj) {
          const crr = [i, obj[i]]
          brr.push([i, obj[i], this.ruleSum(crr)])
          benefitSum += Number(this.ruleSum(crr).benefit)
        }
        return [brr, arr, benefitSum.toFixed(2)]
      },
      checkAll () {
        let isAllChecked = false
        if (this.activeCartIndex === 0) {
          // checedList 扁平化处理
          let flattenChecklist = flattenDepth(this.checkedList, 2)
          isAllChecked = flattenChecklist.indexOf(-1) < 0
        } else {
          isAllChecked = this.checkedList[this.activeCartIndex - 1].indexOf(-1) < 0
        }
        return isAllChecked
      },
      // 当前选中的商品列表
      activeGoods () {
        let goods = []
        let selectedId = []
        let _arrstock = []
        if (!this.cartList.length) return
        this.cartList.map((cart, cartIndex) => {
          if (cartIndex !== 0) return
          cart.productList.map(async (product, productIndex) => {
            let _good = product
            _good.checked = this.checkedList[cartIndex][productIndex] === 1
            // 库存限制
            if (_good.checked && _good.stockLimit && (_good.stock === 0 || _good.number > _good.stock)) {
              _good.checked = !_good.checked
              let _arr = this.checkedList[cartIndex]
              _arr[productIndex] = -1
              this.$set(this.checkedList, cartIndex, _arr)
              if (_good.number > _good.stock && _good.stock !== 0) {
                _good.overstock = true
                let res = await changeProNumber(this.shopcartId, '', _good.id, _good.stock, 1)
                if (res.data.resultCode && res.data.resultCode === 2000) {
                  _good['number'] = _good.stock
                  this.$set(this.cartList[0].productList, productIndex, _good)
                }
              }
              return
            }
            if (_good.checked && _good.stockLimit) {
              _good.overstock = false
            }
            if (_good.checked) {
              selectedId.push(_good.id)
              goods.push(_good)
              // 询货
              let _obj = {}
              _obj[_good.id] = _good.number
              _arrstock.push(_obj)
            }
          })
        })
        // 选中货品的id
        this.selectIdArr = JSON.stringify(selectedId)
        let len = this.selectIdArr.length
        this.selectIdArr = this.selectIdArr.substring(1, len - 1)
        // 选中询货的id,num
        this.strstock = JSON.stringify(_arrstock)
        let objreg = /(\[|\]|"|\{|\})/ig
        this.strstock = this.strstock.replace(objreg, '')
        return goods
      }
    },
    methods: {
      ...mapActions(['fetchCartList', 'fetchBrandActivity']),
      catchErrorImage (e) {
        e.target.src = require('img/newload.png')
      },
      // 通过id找出index
      findIndex (cartIndex, id) {
        let goodIndex = null
        this.cartList[cartIndex].productList.forEach((item, index) => {
          if (item.id === id) {
            goodIndex = index
            return false
          }
        })
        return goodIndex
      },
      // 活动规则
      async activityPromotion (fun) {
        let res = await activityFull(1, 1, null)
        res = res.data
        if (res.resultCode === 2000) {
          res.data.voList.forEach((item) => {
            this.ruleReady = true
            this.ruleList[item.id] = {name: item.name, rule: item.discountRuleVOS, bannerUrl: item.detailBannerImgUrl}
          })
        }
        fun()
      },
      // 活动规则文字生成
      ruleText (item0) {
        const rule = this.ruleList[item0[0]].rule || []
        let str = ''
        rule.forEach((item, index) => {
          str += '满' + item.num + '件享' + item.discount * 100 + '折'
          if (index !== rule.length - 1) {
            str += '，'
          }
        })
        return str
      },
      // 活动优惠总价文字 banner地址
      ruleSum (item0) {
        const list = item0[1]
        const rule = this.ruleList[item0[0]]
        let str = ''
        const sum0 = list.reduce((total, cur, i) => { // 普通活动实际总价， 普通活动优惠价， 商品总数量
          let pri1 = total[0]
          let pri2 = total[1]
          let sum1 = total[2]
          if (cur.checked) {
            pri1 += Number((cur.number * cur.productPrice - cur.pmtAmount).toFixed(2))
            pri2 += Number(cur.pmtAmount)
            sum1 += Number(cur.number)
          }
          return [pri1, pri2, sum1]
        }, [0, 0, 0])
        let sum1 = sum0[2] // 商品实际数量
        let sum2 = sum0[2] // 商品区间最小数量
        let per = 1 // 实际折扣
        let pri3 = sum0[0] // 商品原价（普通活动实际总价）
        rule.rule.forEach((item, index) => {
          str += '满' + item.num + '件享' + Math.round(item.discount * 1000) / 100 + '折'
          if (index !== rule.rule.length - 1) {
            str += '，'
          }
          if (item.num <= sum1) {
            per = item.discount
            sum2 = item.num
          }
        })
        let pri4 = (pri3 * per).toFixed(2)
        return {
          bannerUrl: rule.bannerUrl,
          benefit: (pri3 - pri4).toFixed(2), // 优惠金额
          pri: pri4, // 优惠后价格
          pri0: pri3, // 商品原价
          per, // 实际折扣
          sum0: sum1, // 实际数量
          sum: sum2, // 商品优惠区间数量
          str,
          name: rule.name
        }
        // return [`￥ ${pri4} `, `（已优惠 ￥${(pri3 - pri4).toFixed(2)}）`, rule.name]
      },
      // 活动时间判断
      isOverTime (timeEnd) {
        if (!timeEnd) return
        let now = new Date()
        let getTime = now.getTime()
        let endTime = new Date(timeEnd.replace(/-/g, '/')).getTime()
        // 过期
        if (getTime >= endTime) {
          return true
        } else {
          return false
        }
      },
      // 送券活动
      async fetchVoucherActivity () {
        let res = await voucherActivity()
        this.voucherActList = (res.data.data && res.data.data.voList[0]) || {}
        // 周周活动结束.
        if (!('id' in this.voucherActList)) {
          return
        }
        let startTimeParm = this.voucherActList.startTime
        let endTimeParm = this.voucherActList.endTime
        const starTimeStamp = (new Date(startTimeParm.replace(/-/g, '/'))).getTime()
        const endTimeStamp = (new Date(endTimeParm.replace(/-/g, '/'))).getTime()
        let nowTime = (new Date()).getTime()
        // 周周活动开始
        if (nowTime > starTimeStamp && nowTime <= endTimeStamp) {
          this.voucherStatus = true
          return
        }
        // 周周活动还未开始或已结束
        if (nowTime < starTimeStamp || nowTime > endTimeStamp) {
          this.voucherStatus = false
        }
      },
      // 批量询货
      async fetchBatchInquire () {
        if (!this.strstock) {
          this.$message.error('请先选择商品再发起库存咨询')
          return false
        }
        let res = await getBatchConsult(this.strstock)
        if (res.data.resultCode && res.data.resultCode === 2000) {
          res = res.data.data
          this._initShopcart()
        }
      },
      // 获取购物车内的货品列表
      _initShopcart (type = '') {
        let getmoreIds = JSON.parse(getSession('getmoreIds'))
        this.fetchCartList().then((res) => {
          this.getCartList()
          this.initCheckedList()
          if (type === 'getmore') {
            let _arr = this.checkedList[0]
            res[0]['productList'].forEach((item, index) => {
              if (getmoreIds.includes(item.productId)) {
                item.checked = true
                _arr[index] = 1
              }
            })
            this.$set(this.checkedList, 0, _arr)
          } else if (type === 'mounted') {
            this.select(1)
          }
        })
      },
      getCartList () {
        let arrayList = []
        const cartList = JSON.parse(JSON.stringify(this.cartLists))
        cartList[0].productList.forEach((item) => {
          item.checked = true
        })
        this.cartList = cartList
        arrayList = this.cartList[0]['productList']
        if (arrayList.length > 0) {
          arrayList.map((item, index) => {
            if (this.getMoreGoodsOver.length) {
              this.getMoreGoodsOver.map((moreItem, moreInd) => {
                if (moreItem.productId === item.productId) {
                  item['moreText'] = moreItem.msg
                }
              })
            }
          })
          this.$set(this.cartList[0], 'productList', arrayList)
        }
      },
      goodChecked (cartIndex, goodIndex) {
        let _arr = this.checkedList[cartIndex]
        _arr[goodIndex] = _arr[goodIndex] === -1 ? 1 : -1
        this.$set(this.checkedList, cartIndex, _arr)
      },
      initCheckedList () {
        let nowTime = (new Date()).getTime()
        let _arr = []
        if (this.cartList.length > 0) {
          // 循环购物车数组
          this.cartList.map((cart, cartIndex) => {
            if (!_arr[cartIndex]) {
              _arr[cartIndex] = []
            }
            // 如果购物车中商品不为空
            if (cart.productList.length > 0) {
              let productList = cart.productList // 货品列表

              // 循环货品列表
              productList.map((spuItem, spuIndex) => {
                let endTime = spuItem.endTime && (new Date(spuItem.endTime.replace(/-/g, '/'))).getTime()
                if (!_arr[cartIndex][spuIndex]) {
                  _arr[cartIndex][spuIndex] = -1
                }
                // 状态为缺货商品
                if (spuItem.activity && nowTime > endTime) {
                  _arr[cartIndex][spuIndex] = 2 // 缺货商品 checked值 为2
                }
              })
            }
          })
        }
        this.checkedList = _arr
      },
      select (type) {
        // type -1: 取消全选 1： 选中全部
        this.checkedList.map((cart, cartIndex) => {
          this.setSeletedListPatch(cartIndex, type)
        })
      },
      setSeletedListPatch (index, type) {
        let _list = this.checkedList[index]
        let _arr = []
        _list.forEach(element => {
          element !== 2 ? _arr.push(type) : _arr.push(2)
        })
        this.$set(this.checkedList, index, _arr)
      },
      // 全选
      goodAllChecked () {
        if (this.checkAll) {
          this.select(-1)
        } else {
          this.select(1)
        }
      },
      // 删除商品
      async deleteSku (id) {
        let res = await deleteCart(id)
        if (res.data.resultCode && res.data.resultCode === 2000) {
          this._initShopcart()
        }
      },
      // 删除单个商品
      deleteSingle (cartIndexT, productIndexT, id) {
        this.$confirm('是否要删除此商品', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteSku(id)
        }).catch(() => {
        })
      },
      // 删除选中的商品
      deleteSelected () {
        if (this.selectIdArr === '') {
          this.$message({
            message: '还没有选择任何商品'
          })
          return
        }
        this.$confirm('是否要删除选中的商品', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteSku(this.selectIdArr)
          this.selectIdArr = '' // 选中的ids 变成空
        }).catch(() => {})
      },
      // 修改货品数量
      async inputAmount (value, cartIndex, skuIndex, objitem) {
        let step = objitem.packingNum
        // 输入框里删除的情况下为undefined，处理方式为改为最低数量step
        if (value === undefined) {
          this.cartList[cartIndex]['productList'][skuIndex]['number'] = step
          value = step
        }
        // 如果不存在id 请求购物车
        if (!this.shopcartId) {
          this.fetchCartList()
          this.shopcartId = this.$store.state.shopcart.shopCartId
        }
        // 计算倍数
        let lastNum = value % step
        if (lastNum !== 0) {
          this.$message({
            message: `此商品盒装数${step}`
          })
        }
        let leftNum = lastNum === 0 ? value : value - lastNum + step
        let _arr = this.cartList[cartIndex]
        let curObj = _arr['productList'][skuIndex]
        // 个人限购 商品不限购
        if (curObj.personalLimited) {
          if (curObj.stockLimit && leftNum > curObj.stock) {
            leftNum = curObj.stock
            this.$message(`您的选购数量已达库存数量`)
          } else if (curObj.lastPersonalLimitNum === 0 || leftNum > curObj.lastPersonalLimitNum) {
            leftNum = curObj.lastPersonalLimitNum
            this.$message(`抱歉,此商品限购期间每人限购${curObj.personalLimitNum}件,您已达此商品的添加上限`)
          } // 商品限购
        } else if (curObj.stockLimit && leftNum > curObj.stock) {
          this.$message('您的选购数量已达库存数量')
          leftNum = curObj.stock
        }
        // 设置购物车数额
        _arr['productList'][skuIndex]['number'] = leftNum
        this.$set(this.cartList, cartIndex, _arr)
        this.$nextTick(() => {
          this.$refs[`prod_${skuIndex}`][0].setCurrentValue(leftNum)
        })
        // 重新请求购物车数量
        let res = await changeProNumber(this.shopcartId, '', objitem.id, leftNum, 1)
        if (res.data.resultCode && res.data.resultCode === 2000) {
          _arr['productList'][skuIndex]['number'] = leftNum
          this.$set(this.cartList, cartIndex, _arr)
          await this.fetchCartList().then((res) => {
            this.getCartList()
          })
        } else {
          this.$message.error(res.data.resultMsg || '网络错误')
        }
      },
      // 提交订单
      submitOrder () {
        // 选中的ids字符串
        this.$store.commit('SELECTIDS', this.selectIdArr)
        // mutations 选中的数组对象
        this.$store.commit('SELECTEDPROLIST', this.activeGoods)
        this.$router.push({name: 'OrderInfo', query: {count: this.activeAmount}})
      },
      // 返回上一页
      goBack () {
        this.$router.go(-1)
      },
      // 存在活动再执行
      activityTime () {
        this.fetchBrandActivity().then(res => {
          this.openedActList = (res && res.voList[0]) || {}

          // 周周活动结束
          if (!('id' in this.openedActList)) {
            return
          }
          let startTimeParm = this.openedActList.startTime
          let endTimeParm = this.openedActList.endTime
          const starTimeStamp = (new Date(startTimeParm.replace(/-/g, '/'))).getTime()
          const endTimeStamp = (new Date(endTimeParm.replace(/-/g, '/'))).getTime()
          let nowTime = (new Date()).getTime()
          // 周周活动开始
          if (nowTime > starTimeStamp && nowTime <= endTimeStamp) {
            this.fielsStatus = 1
            this.startCountFn(endTimeParm)
            return
          }
          // 周周活动还未开始
          if (nowTime < starTimeStamp) {
            this.startCountFn(startTimeParm)
          }
          // 周周活动结束
          if (nowTime > endTimeStamp) {
            this.timerText = '本场活动结束'
            this.fielsStatus = 2
          }
        })
      },
      // 倒计时 2018-09-10 2018-09-30
      startCountFn (timeParm) {
        let vm = this
        if (vm.globalTimer !== null) {
          window.clearTimeout(vm.globalTimer)
        }
        vm.globalTimer = setTimeout(function () {
          vm.timerresult = countDown(timeParm)
          // 剩余时间<=0
          if (vm.timerresult + '' === 'false') {
            vm._initShopcart('mounted')
            window.clearTimeout(vm.globalTimer)
            vm.globalTimer = null
            return false
          }
          vm.startCountFn(timeParm)
        }, 1000)
        // vm.globalTimer = timer
      }
    },
    mounted () {
      let getmoreIds = getSession('getmoreIds')
      // this.activityTime() // 活动
      this.fetchVoucherActivity() // 送券
      this.activityPromotion(() => {
        if (getmoreIds) {
          this._initShopcart('getmore')
        } else {
          this._initShopcart('mounted')
        }
      })
      if (!this.cartLength) return
      let vm = this
      setTimeout(function () {
        let refsubmit = vm.$refs.refSubmit || null
        if (this.cartLength > 0) this.select(1)
        window.onscroll = throttle(function () {
          var clientH
          var scrollH
          var scrollT
          var bottomH
          if (document.documentElement) {
            clientH = document.documentElement.clientHeight
            scrollH = document.documentElement.scrollHeight
          } else if (document.body) {
            clientH = document.body.clientHeight
            scrollH = document.body.scrollHeight
          }
          scrollT = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop
          bottomH = scrollH - clientH - scrollT
          if (bottomH > 500 && refsubmit) {
            // submit_order
            refsubmit.className = 'submit_box fixed_submit'
          } else if (refsubmit) {
            refsubmit.className = 'submit_box'
          }
        }, 100)
      }, 2000)
    },
    beforeDestroy () {
      window.clearTimeout(this.globalTimer)
      this.globalTimer = null
      window.onscroll = ''
    },
    beforeRouteLeave (to, from, next) {
      removeSession('getmoreIds')
      next()
    },
    watch: {
      // 选中的商品
      activeGoods (newCart) {
        let [activeAmount, selectedPrice] = [0, 0]
        if (newCart && newCart.length > 0) {
          newCart.map((skuItem, newCartIndex) => {
            // 选中
            if (skuItem.checked && skuItem !== 0) {
              activeAmount += parseInt(skuItem.number)
              this.activeAmount = activeAmount
              let pmtAmount = skuItem.pmtAmount > 0 ? skuItem.pmtAmount : 0
              selectedPrice += parseFloat(skuItem.number * skuItem.productPrice - pmtAmount)
              this.selectedPrice = selectedPrice.toFixed(2)
            } else {
              this.activeAmount = activeAmount
              this.selectedPrice = selectedPrice.toFixed(2)
            }
          })
        } else {
          this.activeAmount = 0
          this.selectedPrice = 0
        }
      },
      // 购物车里的商品
      cartList: {
        handler: function (newVal) {
          this.allAmount = 0
          if (newVal) {
            newVal.map((item, index) => {
              // if (index === 0) {
              //   this.shopcartId = item.id
              // }
              if (item.productList.length > 0) {
                item.productList.map((proItem, proIndex) => {
                  this.allAmount += proItem.number
                })
              }
            })
          }
        },
        deep: true
      },
      $route: {
        handler: function (to, from) {
          if (from.name === 'orderManage') {
            let getmoreIds = getSession('getmoreIds')
            getmoreIds && this.getMoreProduct() // 获取再来一单的ids
          }
        },
        // 深度观察监听
        deep: true
      }
    },
    filters: {
      tofiexed (value) {
        let num = (1 - value) * 100
        return num.toFixed(1)
      },
      endTimeFilter (value) {
        if (!value) return '00:00'
        let time = value.split(' ')[1].substr(0, 5)
        return time
      }
    }

  }
</script>
<style lang="scss" scoped>
  .shopcart-bt{
    margin-bottom: 2px;
    &:last-child{
      margin-bottom: 0;
    }
  }
  .knife_container{
    margin-top: 30px;
  }
  .act-title{
    font-size: 12px;
    margin: 0;
    height: 38px;
    background-color: #FF7300;
    color: #fff;
    line-height: 38px;
    overflow: hidden;
    &.gray{
      background-color: #EEEEEE;
      color: #333333;
    }
    a{
      color: #fff;
      float: right;
      margin-right: 40px;
    }
    .act-content{
      float: right;
      margin-right: 32px;
    }
    .act-tag{
      float: left;
      display: inline-block;
      box-sizing: border-box;
      margin-left: 20px;
    }
  }
  .act-footer{
    height: 50px;
    line-height: 50px;
    text-align: center;
    font-size: 12px;
    background-color: #fff;
    color: #999999;
    border-top: 2px dashed #F8F8F8;
    margin-top: -2px;
    span{
      font-size: 14px;
      color: #F45923;
    }
  }
  @mixin wh($width, $height){
    width: $width;
    height: $height;
  }
  $org_color: #F55923;
  .shopcart_data_no {
    margin: 200px auto;
    text-align: center;
    .shopcart-text{
      margin-top: 30px;
      font-size:16px;
      color:rgba(51,51,51,1);
      line-height:22px;
    }
    .shopcart_no_btn{
      display: inline-block;
      width:200px;
      height:50px;
      background:rgba(255,204,0,1);
      border-radius:5px;
      text-align: center;
      line-height: 50px;
      margin-top: 30px;
      color: #333333;
    }
  }

    // 缺货
    .OOS{
      position: absolute;
      font-size: 14px;
      color: #fff;
      width: 40px;
      height: 20px;
      line-height: 20px;
      border-radius: 2px;
      background: #ff0000;
      top: -10px;
      left: 0;
    }
    .shopcart_wrapper{
      margin-bottom: 30px;
    }
    .spanbox{
      @include wh(20px, 20px);
      position: absolute;
      display: inline-block;
      vertical-align: middle;
      top: 24px;
      left: 30px;
    .checkcss{
      position: absolute;
      @include wh(20px, 20px);
      z-index: 5;
      opacity: 0;
    }
    .checkspan{
      @include wh(20px, 20px);
      display: inline-block;
    }
     input[type='checkbox'].checkcss + span:after{
       position: absolute;
       @include wh(22px, 22px);
       font-family: 'iconfont';
       content: "\e7c0";
       top: 0;
      left: 2px;
      font-size: 18px;
      color: #dcdcdc;
    }
     input[type='checkbox'].checkcss:checked + span:after{
       content: "\e683";
      color: #FFCC00;
    }
  }
  .check-el{
    position: relative;
  }
  .headcheckbox {
     input[type='checkbox'].checkcss + span:after{
       position: absolute;
       @include wh(22px, 22px);
       font-family: 'iconfont';
       content: "\e7c0";
       top:-24px;
      left: 0;
      color: #dcdcdc;
    }
     input[type='checkbox'].checkcss:checked + span:after{
       content: "\e683";
      color: #FFCC00;
    }
  }

  .shop_nav{
    position: relative;
    padding: 24px 0 18px;
    .active_bar{
      @include wh(120px, 2px);
      position: absolute;
      bottom: 20px;
      left: 0;
      background-color: #333333;
      z-index: 1;
      top: 64px;
      transition: transform .3s cubic-bezier(.645,.045,.355,1);
      list-style: none;
    }
    & > span{
      font-size: 18px;
      color: #333;
      padding: 0 24px 16px;
      line-height: 25px;
      &:first-child{
        border-left: none;
      }
    }

  }
  .shopcart_tabhead{
    height: 60px;
    line-height: 60px;
    text-align: center;
    font-size: 14px;
    color: #474747;
    background: #ffffff;
    .header-choose{
      display:inline-block;
      width: 50px;
      text-align: center;
    }
  }
  .line-gray{
    height: 50px;
    background: #F8F8F8;
    line-height: 50px;
  }
  .head-stock{
    text-align: right;
    padding-right: 40px;
  }
  .head-product-total{
    padding-left: 45px;
    text-align: left;
  }
  .shopcart_body{
    text-align: center;
    .shopcart_body_img{
      position: relative;
      display:inline-block;
      @include wh(70px, 70px);
      vertical-align: top;
      margin-left: 15px;
      & > img{
        width: 100%;
        height:100%;
      }
    }
    .shopcart_img_text{
      width:238px;
      display:inline-block;
      line-height:2.0;
      padding-left: 12px;
      font-size: 14px;
      .shopcart_productname{
        line-height: 20px;
      }
    }
    .good_spe{text-align: left;}
    .wid10, .wid8, .wid7, .wid5, .wid4, .wid3 {
      height:70px;line-height:70px;display: inline-block;
    }
    .pmt_price{
      line-height: 30px;
      color: #ff0000;
    }
    .good_price{
      line-height: 50px;
    }
    .old_price{
      line-height: 20px;
      color: #999;
      text-decoration: line-through;
      font-size: 12px;
    }
    .good_stock {
      font-size: 14px;
      text-align: center;
      text-align: right;
      padding-right: 40px;
      box-sizing: border-box;
    }
    .wid10{ width: 41.66667%;}
    .wid8{ width: 33.33333%;}
    .wid7{ width: 29.16667%;}
    .wid5{ width: 20.83333%;}
    .wid4{width: 16.66667%;}
    .wid3{width: 12.5%;}
    .wid2X{width: 8.33333%;display: inline-block;padding: 10px 0;height: 50px;font-size: 16px;}
    .wid2{ height:40px;display: inline-block;width: 8.33333%;}
  }
  .shopcart_title{
    height: 30px;
    line-height: 30px;
    padding-left: 15px;
    color: #666;
    font-size: 14px;
  }
  .goods-box{
    position: relative;
    margin-top: 20px;
    font-size: 0;
  }
  .good_info_li{
    position: relative;
    display: inline-block;
    color: #474747;
    width: 100%;
    padding: 22px 0;
    background-color: #ffffff;
    .disabled-mask{
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      background: rgba(247,247,247, 0.5);
      z-index: 88;
    }
    &.disabled{
      background-color: rgba(255, 255, 255, 0.2);

      color: #999;
    }
    & >div{
      float: left;
      vertical-align: middle;
    }
    .good_total{
      font-size: 18px;
      font-weight: 600;
      color: $org_color;
      padding-left: 45px;
      text-align: left;
      box-sizing: border-box;
    }
    .active-price{
      line-height: 2;
    }
    .prefer-price{
      color: #474747;
      font-size: 12px;
    }
    .disabled-text{
      color: #999;
      // text-decoration: line-through;
    }
  }
  .good_check{
    display: table-cell;
    vertical-align: top;
    margin: 17px 5px 0 0;
  }
  .good_infos{
    width: 87.5%;
    display: table-cell;
  }
  .good_oprate{
    // display: inline-block;
    // width: 14%;
    // text-align: center;
    // color: #CBCBCB;
    cursor: pointer;
    z-index:90;
    position: absolute;
    width: 99px;
    height: 70px;
    line-height: 70px;
    right: 0;
  }
  .submit_box{
    height: 135px;
    margin-top: -145px;
  }
  .check-two{
    width: 100px;
    display: inline-block;
    position: relative;
    left: -28px;
  }
  .submit_order{
    position: relative;
    // display: flex;
    // justify-content: space-between;
    margin: 0 auto;
    height: 60px;
    padding-left: 28px;
    line-height: 60px;
    font-size: 14px;
    color: #333333;
    background-color: #ffffff;
    // overflow: hidden;
    .btn_text{
      padding-right: 10px;
      cursor: pointer;
    }
    .submit_price{
      font-size: 24px;
      color: $org_color;
      vertical-align: sub;
    }
  }
  .submit-box{
    margin-top: 30px;
  }
  .fixed_submit{
    position: fixed;
    bottom: 1px;
    z-index: 500;
    background: #f8f8f8;
    width: 1200px;
    border: 1px solid #f2f2f2;
    box-sizing: border-box;
  }
  .subm-button{
    display: inline-block;
    white-space: nowrap;
    cursor: pointer;
    -webkit-appearance: none;
    text-align: center;
    box-sizing: border-box;
    outline: none;
    margin: 0;
    -webkit-transition: .1s;
    transition: .1s;
    font-weight: 500;
    user-select: none;
    font-size: 14px;
    border: 1px solid #ffcc00;
  }
  .submit_btn{
    // float: right;
    width: 200px;
    background: #FFCC00;
    margin-left: 19px;
    line-height: 56px;
    color: #333;
    font-size: 16px;
  }
  .not_allow{
    cursor: not-allowed;
  }
  //  计数器
  .input-num-self{
    width: 138px;
  }
  .order-notice-box{
    height:62px;
    background:rgba(255,245,206,1);
    box-shadow:0px 2px 1px 0px rgba(0,0,0,0.05);
    font-size:16px;
    line-height: 62px;
    color: #333333;
    padding-left: 20px;
  }
  .fixed-notice{
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 5;
  }
  .discount-tag1{
    position: absolute;
    color: #fff;
    top: 0;
    left: 0;
    background: rgba(255,0,0,1);
    // width: 36px;
    height: 25px;
    line-height: 25px;
    text-align: center;
    border-radius: 0;
    padding: 0 2px;
    font-size: 12px
  }
  .discount-time{
    line-height: 20px;
    font-size:14px;
    color:rgba(255,0,0,1);
    border: 1px solid rgba(255,0,0,1);
    padding: 1px 4px;
  }
  .overstock {
    margin: -10px auto 0;
    display: table;
  }
  .shop-notice-wrapper{
    margin-bottom: 10px;
    height: 62px;
    background: rgba(255,245,206,1);
    line-height: 62px;
    padding-left: 30px;
    padding-right: 40px;
    .watch-detail{
      float:right;
      color: #009CFF;
      font-size: 14px;
    }
  }
  .fc-blue{
    color: #009CFF;
  }
</style>
<style>
  .el-input-number__increase, .el-input-number__decrease{
    background: #ffffff;
  }
  .el-input-number .el-input__inner {
    -webkit-appearance: none;
    padding-left: 40px;
    padding-right: 40px;
    text-align: center;
  }
</style>

<style lang="scss">
.el-tabs__item {
  font-size:16px;
}
.dialogorderinfocomfirm {
  .el-dialog__header{
    border-bottom: 1px dashed #EEEEEE;
    padding-top: 25px!important;
    box-sizing: border-box;
    height: 64px;
    .el-dialog__title{
      font-size: 18px;
      color: #303030!important;
    }
  }
  .el-button{
    height: 50px;
    color: #303030;
  }
  .dialogGrayBtn{
    background-color: #E0E0E0;
    color: #999999;
  }
}

.el-dialog--center .el-dialog__body {
    text-align: initial;
    padding: 45px 27px 35px;
  }
</style>

